<template>
  <div id="shopcart-tpl">
    <div v-if="goods.length">
      <!--购物车内容列表 -->
    </div>
    <h2 v-else>
      购物车为空
    </h2>
    <table border="1" align="center" width="500">
      <caption>
        <h2>购物车</h2>
      </caption>
      <thead>
        <tr>
          <th></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in goods" :key="index" align="center">
          <td>{{ index+1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ filter(item.price) }}</td>
          <td>
            <button @click="decrement(index)" v-bind:disabled="item.count <= 0">
              -
            </button>
            {{ item.count }}
            <button @click="increment(index)">+</button>
          </td>
          <td>
            <button @click="removeHandle(index)">移除</button>
          </td>
        </tr>
        <tr align="center">
          <td colspan="2">总价格</td>
          <td colspan="3">{{ filter(computedName) }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import { reactive, toRefs, computed, onMounted } from 'vue'

export default {
  name: 'ShopCartTpl',
  setup () {
    const state = reactive({
      goods: []
    })
    onMounted(() => {
      fetch('/goods.json')
        .then(res => res.json())
        .then(res => {
          state.goods = res.data
        })
    })
    const decrement = (index) => {
      state.goods[index].count--
    }
    const increment = (index) => {
      state.goods[index].count++
    }
    const removeHandle = (index) => {
      state.goods.splice(index, 1)
    }
    const filter = (price) => {
      return '￥' + price.toFixed(2)
    }
    const computedName = computed(() => {
      let totalPrice = 0
      for (let i = 0; i < state.goods.length; i++) {
        totalPrice += state.goods[i].price * state.goods[i].count
      }
      return totalPrice
    })
    return {
      ...toRefs(state),
      computedName,
      decrement,
      increment,
      removeHandle,
      filter
    }
  }
}
</script>

<style scoped lang="scss"></style>
